package com.adk.backend.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传工具类（阿里云OSS）
 */
@Slf4j
@Component
public class FileUploadUtil {
    
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    
    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;
    
    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;
    
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    
    /**
     * 上传文件到OSS
     */
    public String uploadFile(MultipartFile file, String folder) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        // 生成唯一文件名
        String fileName = folder + "/" + UUID.randomUUID().toString() + extension;
        
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            InputStream inputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            ossClient.putObject(putObjectRequest);
            
            // 返回文件URL
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    
    /**
     * 删除OSS文件
     */
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return;
        }
        
        // 从URL中提取文件路径
        String fileName = fileUrl.substring(fileUrl.indexOf(bucketName) + bucketName.length() + 1);
        
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, fileName);
        } catch (Exception e) {
            log.error("文件删除失败", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    
    /**
     * 上传文件到本地（用于投递单等模块）
     * @param file 文件
     * @param folder 文件夹路径（相对于项目根目录，如 "uploads/do"）
     * @param userId 用户ID
     * @param prefix 文件名前缀（如 "pl", "bl"）
     * @return 文件路径（相对于项目根目录，如 "./uploads/do/xxx.jpg"）
     */
    public String uploadFileToLocal(MultipartFile file, String folder, Integer userId, String prefix) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        // 文件大小限制：50MB
        long maxFileSize = 50 * 1024 * 1024; // 50MB
        if (file.getSize() > maxFileSize) {
            throw new RuntimeException("文件大小不能超过50MB");
        }
        
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new RuntimeException("文件名不能为空");
            }
            
            // 获取文件扩展名
            String extension = "";
            if (originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 验证文件类型
            String lowerExtension = extension.toLowerCase();
            String[] allowedTypes = {".pdf", ".jpg", ".jpeg", ".png", ".xlsx", ".xls", ".csv", ".txt", ".7z", ".zip", ".rar"};
            boolean isValidType = false;
            for (String type : allowedTypes) {
                if (lowerExtension.equals(type)) {
                    isValidType = true;
                    break;
                }
            }
            if (!isValidType) {
                throw new RuntimeException("不支持的文件类型，仅支持：pdf, jpg, jpeg, png, xlsx, xls, csv, txt, 7z, zip, rar");
            }
            
            // 创建上传目录
            java.io.File uploadDir = new java.io.File(folder);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成文件名：userId-prefix-timestamp序号.扩展名
            long timestamp = System.currentTimeMillis() / 1000;
            String fileName = userId + "-" + (prefix != null ? prefix + "-" : "") + timestamp + extension;
            
            // 保存文件
            java.io.File targetFile = new java.io.File(uploadDir, fileName);
            file.transferTo(targetFile);
            
            // 返回相对路径（兼容PHP格式）
            return "./" + folder + "/" + fileName;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("本地文件上传失败", e);
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除本地文件
     */
    public boolean deleteLocalFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }
        
        try {
            // 移除 "./" 前缀（如果有）
            String cleanPath = filePath.startsWith("./") ? filePath.substring(2) : filePath;
            java.io.File file = new java.io.File(cleanPath);
            if (file.exists()) {
                return file.delete();
            }
            return false;
        } catch (Exception e) {
            log.error("删除本地文件失败", e);
            return false;
        }
    }
    
    /**
     * 创建ZIP文件并返回文件流
     */
    public java.io.File createZipFile(java.util.List<String> filePaths, String zipFileName) {
        try {
            // 确保临时目录存在
            java.io.File zipFile = new java.io.File(zipFileName);
            java.io.File parentDir = zipFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }
            
            java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(
                new java.io.FileOutputStream(zipFile)
            );
            
            for (String filePath : filePaths) {
                String cleanPath = filePath.startsWith("./") ? filePath.substring(2) : filePath;
                java.io.File file = new java.io.File(cleanPath);
                if (file.exists() && file.isFile()) {
                    java.util.zip.ZipEntry entry = new java.util.zip.ZipEntry(file.getName());
                    zos.putNextEntry(entry);
                    
                    java.io.FileInputStream fis = new java.io.FileInputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                    fis.close();
                    zos.closeEntry();
                }
            }
            
            zos.close();
            return zipFile;
        } catch (Exception e) {
            log.error("创建ZIP文件失败", e);
            throw new RuntimeException("创建ZIP文件失败：" + e.getMessage());
        }
    }
}


